﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using System.Collections.Specialized;

namespace Facebook_Graph_Toolkit {
    /// <summary>
    /// Inherit this class in a page that is not inside a Facebook Canvas App page to bring Facebook integrations to this page
    /// </summary>
    public class SocialPage : System.Web.UI.Page {
        #region basic properties
        /// <summary>
        /// Whether the user is required to authorize the application to view this page
        /// </summary>
        public bool RequireLogin = false;
        /// <summary>
        /// The user will be prompted to grant these Extended Permissions at authorization
        /// </summary>
        public string ExtendedPermissions = "";

        private GraphApi.Api _Api = null;
        /// <summary>
        ///Stores the current Access Token and provides methods to make Api calls
        /// </summary>
        public GraphApi.Api Api {
            get {
                return _Api;
            }
        }
        #endregion

        /// <summary>
        /// Manages Facebook Application configuration of this page
        /// </summary>
        public FacebookAppConfig FacebookAppConfigManager = new FacebookAppConfig();

        /// <summary>
        /// Redirect the user to authorize the Application
        /// </summary>
        protected void RedirectToFacebookAuthorization() {
            FacebookAppConfigManager.GetDefaultConfig();
            string AuthorizeUrl = String.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", FacebookAppConfigManager.FacebookAppID, Request.Url.AbsoluteUri, ExtendedPermissions);
            Response.Redirect(AuthorizeUrl, true);
        }
        
        /// <summary>
        /// Event handler of 'OnLoad' event
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e) {
            if (Session["GraphApi"] != null) {
                _Api = (GraphApi.Api)Session["GraphApi"];
                if (_Api.Expires != null) if (_Api.Expires < DateTime.UtcNow) RedirectToFacebookAuthorization();
                
            } else {
                FacebookAppConfigManager.GetDefaultConfig();
                if (!string.IsNullOrEmpty(Request.QueryString["code"])) {
                    _Api = Helpers.ApiProducer.GetApiFromCode(this.Context, FacebookAppConfigManager);
                    Session["GraphApi"] = _Api;
                } else
                    if (RequireLogin) RedirectToFacebookAuthorization();
            }

            base.OnLoad(e);

        }
    }
}
